package com.hsy.linemoney.requests;

import android.os.AsyncTask;

import com.deparse.dpframe.tools.utils.DPGsonUtil;
import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.LineMoneyContext;
import com.liferay.mobile.android.service.Session;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by MartinKent on 2016/9/9.
 */
public class RequestTask<T> extends AsyncTask<Object, Integer, Object> {
    private final boolean checkStatusCode;
    private Session session;
    private int what;
    private String api;
    private JSONObject params;
    private Callback<T> callback;

    public RequestTask(final int what, final String api, final JSONObject params, final Callback<T> callback, boolean... checkStatusCode) {
        this.session = LineMoneyContext.getSession();
        this.what = what;
        this.api = api;
        this.params = params;
        this.callback = callback;
        this.checkStatusCode = (null == checkStatusCode || checkStatusCode.length < 1) || checkStatusCode[0];
    }

    public static class StatusObj {
        private Status status;

        public void setStatus(Status status) {
            this.status = status;
        }

        public Status getStatus() {
            return this.status;
        }

        public static class Status {
            private String message;

            private String statusCode;

            private String code;

            public void setMessage(String message) {
                this.message = message;
            }

            public String getMessage() {
                return this.message;
            }

            public void setStatusCode(String code) {
                this.statusCode = code;
            }

            public String getStatusCode() {
                return this.statusCode;
            }

            public String getCode() {
                return code;
            }

            public void setCode(String code) {
                this.code = code;
            }
        }
    }

    public static class StatusCodeException extends Exception {
        private String code;
        private String message;

        public StatusCodeException(String code, String detailMessage) {
            super(detailMessage);
            this.code = code;
            this.message = detailMessage;
        }

        public String getCode() {
            return code;
        }

        @Override
        public String getMessage() {
            return "[" + code + "]" + message;
        }

        @Override
        public String getLocalizedMessage() {
            return "[" + code + "]" + message;
        }
    }

    @Override
    protected Object doInBackground(Object... p) {
        try {
            JSONObject cmd = new JSONObject();
            cmd.put(api, params);
            JSONArray array = session.invoke(cmd);
            DPLogUtil.d("RequestTask what=" + what + ", api=" + api + ",params=" + params.toString() + ", result=" + array.toString());
            if (checkStatusCode) {
                DPLogUtil.d("yyy " + array.get(0).toString());
                StatusObj obj = DPGsonUtil.fromJson(array.get(0).toString(), StatusObj.class);
                if (("200".equals(obj.getStatus().getCode()) || "200".equals(obj.getStatus().getStatusCode()))) {
                    return array;
                } else {
                    return new StatusCodeException(obj.getStatus().getCode(), obj.getStatus().getMessage());
                }
            } else {
                return array;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            DPLogUtil.d("RequestTask JSONException what=" + what + ", api=" + api + ",params=" + params.toString() + ", msg=" + e.getLocalizedMessage());
            return e;
        } catch (Exception e) {
            e.printStackTrace();
            DPLogUtil.d("RequestTask Exception what=" + what + ", api=" + api + ",params=" + params.toString() + ", msg=" + e.getLocalizedMessage());
            return e;
        }
    }

    @Override
    protected void onPostExecute(Object result) {
        super.onPostExecute(result);
        if (result instanceof JSONArray) {
            if (null != callback) {
                callback.onSuccess(what, (T) result);
            }
        } else {
            if (null != callback) {
                Exception e = null == result ? new Exception("Result null") : ((Exception) result);
                callback.onError(what, 0, e.getLocalizedMessage(), e);
                e.printStackTrace();
            }
        }
    }

    public void invoke() {
        super.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
